/**
 * 获取当前组件信息
 * @param {*} model 字段名
 * @returns
 */
export function getCurrentScheme(model) {
  if (!model) {
    return
  }
  let scheme = null;
  function getField(arr){
    for(let i= 0; i < arr.length; i++) {
      if(scheme){return}
      if(arr[i].__vModel__ === model){
        scheme = arr[i];
      }
      if(Array.isArray(arr[i].__config__.children)){
        getField(arr[i].__config__.children);
      }
    }
  }
  getField(this.formConfCopy.fields);
  return scheme;
}
/**
 * 获取当前组件配置
 * @param {*} scheme 组件信息
 * @returns
 */
export function getCurrentSchemeConfig(scheme) {
  if (!scheme || !Object.keys(scheme).length === 0) {
    return
  }
  return scheme.__config__
}

/**
 * 设置form值
 */
export function setFormValue(model, value) {
  if (!model) {
    return
  }
  this.$nextTick(() => {
    // 获取当前组件信息
    const currentScheme = getCurrentScheme.call(this, model)
    if (!currentScheme) {
      return
    }
    // 获取当前组件配置
    const currentSchemeConfig = getCurrentSchemeConfig(currentScheme)
    if (!currentSchemeConfig) {
      return
    }
    this.$set(currentSchemeConfig, 'defaultValue', value)
    this.$set(this[this.formConf?.formModel], model, value)
  })
}

/**
 * 设置form组件显隐
 */
export function setFormShowOrHide(model, flag) {
  if (!model || typeof flag !== 'boolean') {
    return
  }
  this.$nextTick(() => {
    // 获取当前组件信息
    const currentScheme = getCurrentScheme.call(this, model)
    if (!currentScheme) {
      return
    }
    this.$set(currentScheme, 'hide', flag)
  })
}

/**
 * 设置form组件必填标识
 */
export function setFormRequired(model, flag) {
  if (!model || typeof flag !== 'boolean') {
    return
  }
  this.$nextTick(() => {
    // 获取当前组件信息
    const currentScheme = getCurrentScheme.call(this, model)
    if (!currentScheme) {
      return
    }
    // 获取当前组件配置
    const currentSchemeConfig = getCurrentSchemeConfig(currentScheme)
    if (!currentSchemeConfig) {
      return
    }
    this.$set(currentSchemeConfig, 'required', flag)
    // rule优先级高于form-item的required，所以还需要设置rules中的required
    if (this[this.formConfCopy?.formRules]) {
      this[this.formConfCopy.formRules][model]?.map((item) => {
        if (Object.prototype.hasOwnProperty.call(item, 'required')) {
          item['required'] = flag
        }
        return item
      })
    }
  })
}

/**
 * 设置form组件是否可用标识
 */
export function setFormDisabled(model, flag) {
  if (!model || typeof flag !== 'boolean') {
    return
  }
  this.$nextTick(() => {
    // 获取当前组件信息
    const currentScheme = getCurrentScheme.call(this, model)
    if (!currentScheme) {
      return
    }
    this.$set(currentScheme, 'disabled', flag)
  })
}

/**
 * 设置form组件的options，比如：select组件
 */
export function setFormFieldOptions(model, options) {
  if (!model || !options || !Array.isArray(options)) {
    return
  }
  this.$nextTick(() => {
    // 获取当前组件信息
    const currentScheme = getCurrentScheme.call(this, model)
    if (
      !currentScheme ||
      !Object.prototype.hasOwnProperty.call(currentScheme, 'options')
    ) {
      return
    }
    this.$set(currentScheme, 'options', options)
  })
}

/**
 * 获取form组件的options，比如：select组件
 */
export function getFormFieldOptions(model) {
  if (!model) {
    return
  }
  // 获取当前组件信息
  const currentScheme = getCurrentScheme.call(this, model)
  if (
    !currentScheme ||
    !Object.prototype.hasOwnProperty.call(currentScheme, 'options')
  ) {
    return
  }
  return currentScheme.options
}

export function getCurrentValue(model) {
  if (!model) {
    return
  }
  return this[this.formConf.formModel][model]
}

export function getSubFormCurrentValue(model,field) {
  if (!model) {
    return
  }
  // 获取当前组件信息
  const currentScheme = getCurrentScheme.call(this, model)
  if (!currentScheme) {
    return
  }
  if(currentScheme.tableData){
    for( let item in currentScheme.tableData[0]){
      if(item === field){
        return currentScheme.tableData[0][item]
      }
    }
  }
}
export async function toRequest(
  url,
  method = 'get',
  data,
  baseURL,
  resolve,
  reject,
  responseType,
  timeout,
  headers
) {
  if (!url) {
    // 是否提示？
    this.$message?.warning('请求url为空！')
    return
  }
  const lowerCaseMethod = method.toLowerCase()
  // 支持的请求方法
  const methods = ['get', 'post']
  if (methods.indexOf(lowerCaseMethod) === -1) {
    this.$message?.warning('不支持的请求方法！')
    return
  }

  const obj = { url, method }

  // 设置请求参数
  if (data) {
    if (method === 'get') {
      obj['params'] = data
    } else if (method === 'post') {
      obj['data'] = data
    }
  }

  if (baseURL) {
    obj['baseURL'] = baseURL
  }

  if (responseType) {
    obj['responseType'] = responseType
  }

  if (timeout) {
    obj['timeout'] = timeout
  }

  if (headers && Object.keys(headers).length > 0) {
    obj['headers'] = headers
  }

  return this.$axios(obj)
    .then((res) => {
      if (resolve) {
        resolve(res)
      }
    })
    .catch((err) => {
      if (reject) {
        reject(err)
      }
    })
}

/**
 * 插入并且设置表单表格数据
 */
export function insertAndSetFormTableData(model, dataObj) {
  // model="table2022127175420110367"; dataObj= {"field103": 111, "field105": 222}
  if (!model || !dataObj || Object.keys(dataObj).length === 0) {
    return
  }
  // 获取当前组件信息
  const currentScheme = getCurrentScheme.call(this, model)
  if (!currentScheme) {
    return
  }
  if (currentScheme.tableData) {
    // 新增一行(不添加数据)
    this.btnFunc('insert', getCurrentSchemeConfig(currentScheme)?.renderKey, [], currentScheme.__config__.editType)
    this.$nextTick(() => {
        // 进行数据填充
        currentScheme.tableData?.forEach((item, index) => {
            // 新增从末位增加，判断最后一行数据
            if (index === currentScheme.tableData.length - 1) {
                for (const key in dataObj) {
                    if (Object.hasOwnProperty.call(item, key)) {
                        this.$set(item, key, dataObj[key])
                    }
                }
            }
      })
      // this.$set(item.__config__, 'defaultValue', event)
      // this.updateTableData({ index: scope?.$index, compObj: item, value: event, renderKey: config.renderKey })
    })
  }
}

/**
 * 通过表单表格数据设置其他组件值
 */
export function setFormValueByTableData(
  tableModel,
  otherModel,
  value
) {
  if (!tableModel || !otherModel) {
    return
  }
  // 获取当前表格组件信息
  const currentTableScheme = getCurrentScheme.call(this, tableModel)
  if (!currentTableScheme) {
    return
  }
  // 目前只针对一行，后期可扩展更新指定行数据
  if (currentTableScheme.tableData && currentTableScheme.tableData.length > 0) {
    currentTableScheme.tableData.forEach((element) => {
      if (Object.hasOwnProperty.call(element, otherModel)) {
        element[otherModel] = value;
      }
    })
  }
}

/**
 * 绑定事件脚本
 */
export async function bindEventScript(event, currentModel, scriptText) {
  const setValue = (model, value) => setFormValue.call(this, model, value)
  const setShowOrHide = (model, flag) =>
    setFormShowOrHide.call(this, model, flag)
  const setRequired = (model, flag) => setFormRequired.call(this, model, flag)
  const setDisabled = (model, flag) => setFormDisabled.call(this, model, flag)
  const request = async(
    url,
    method,
    data,
    baseURL,
    resolve,
    reject,
    responseType,
    timeout,
    headers
  ) =>
    toRequest.call(
      this,
      url,
      method,
      data,
      baseURL,
      resolve,
      reject,
      responseType,
      timeout,
      headers
    )
  const getValue = (model) => getCurrentValue.call(this, model)
  const getSubFormValue = (model,field) => getSubFormCurrentValue.call(this, model,field)
  const getFieldOptions = (model) => getFormFieldOptions.call(this, model)
  const setFieldOptions = (model, options) =>
    setFormFieldOptions.call(this, model, options)
  /* 定制函数，也可通过写自定义脚本实现 */
  const insertAndSetTableData = (model, dataObj) =>
   // model="table2022127175420110367"; dataObj= {"field103": 111, "field105": 222}
    insertAndSetFormTableData.call(this, model, dataObj)
  const setValueByTableData = (tableModel, otherModel, value) =>
  // currentModel="field101"; tableModel="table2022127175420110367"; otherModel= "field104"; value = "qqq";
    setFormValueByTableData.call(
      this,
      tableModel,
      otherModel,
      value
    )

  const formData = this[this.formConf?.formModel]

  let eventScript = null
  // try {
    // 解析事件脚本
    eventScript = new Function(
      'data', // 只针对当前组件的脚本事件
      'currentModel', // 只针对当前组件的脚本事件
      'formData',
      'setValue',
      'getValue',
      'getSubFormValue',
      'setShowOrHide',
      'setRequired',
      'setDisabled',
      'request',
      'getFieldOptions',
      'setFieldOptions',
      'insertAndSetTableData', // 定制函数
      'setValueByTableData', // 定制函数
      '_this', // 用于自定义写脚本的场景
      scriptText
      /* 通用表单和请求操作 */
      // 'console.log("data: ", data); \n console.log("formData: ", formData); \n setValue("field102", "field102"); \n setShowOrHide("field103", true); \n setRequired("field104", false); \n setDisabled("field105", true); \n ' +
      //   ' request("/system/dept/list-all-simple", "get", "", "http://10.136.106.197:48082/admin-api/", (res) => { \n console.log("-------接口正确返回信息: ", res) \n _this.$message?.warning("状态不对，不能下线！") \n }, (err) => { \n console.log("-------接口异常信息: ", err)}); \n ' +
      //   ' console.log(getFieldOptions("field108")); \n setFieldOptions("field108", [{"label": "xq1", "value": 111}, {"label": "xq2", "value": 222}, {"label": "xq3", "value": 333, "disabled": true, "checked": true}]);'
      /* 定制函数 */
      // 'insertAndSetTableData("table2022127175420110367", {"field103": 111, "field105": 222}); \n'
      // 'setValueByTableData("table2022127175420110367", "field104", "qqq"); \n'
      /* 自定义脚本，insertAndSetTableData */
      // 'const model = "table2022127175420110367"; \n const dataObj = {"field103": 111, "field105": 222}; \n const currentScheme = _this.formConfCopy.fields.find(item => item.__vModel__ === model); \n if (!currentScheme) { \n return; \n }' +
      //   ' \n if (currentScheme.tableData.length === 0) \n { _this.btnFunc("insert6", currentScheme.__config__.renderKey) \n _this.$nextTick(() => { \n currentScheme.tableData.forEach(item => { \n for (const key in dataObj) { \n ' +
      //   ' if (Object.hasOwnProperty.call(item, key)) { \n _this.$set(item, key, dataObj[key]) \n } \n } \n }) \n }) \n}'
      /* 自定义脚本，setValueByTableData */
      // 'const tableModel = "table2022127175420110367"; \n const otherModel = "field104"; \n const value = "qqq"; \n const currentTableScheme = _this.formConfCopy.fields.find(item => item.__vModel__ === tableModel); \n ' +
      //   'if (!currentTableScheme) { \n return; \n } \n if (currentTableScheme.tableData && currentTableScheme.tableData.length > 0) { \n ' +
      //   'const allCurrentModelData = []; \n currentTableScheme.tableData.forEach(element => { \n if (Object.hasOwnProperty.call(element, currentModel)) { \n allCurrentModelData.push(element[currentModel]); \n } \n }) \n ' +
      //   'if (allCurrentModelData.length > 0 && allCurrentModelData.every((item) => item + "" === "1")) { \n setValue.call(_this, otherModel, value) \n } \n }'
    )
    if (eventScript) {
      return eventScript(
        event,
        currentModel,
        formData,
        setValue,
        getValue,
        getSubFormValue,
        setShowOrHide,
        setRequired,
        setDisabled,
        request,
        getFieldOptions,
        setFieldOptions,
        insertAndSetTableData,
        setValueByTableData,
        this
      )
    }
  // } catch (error) {
  //   console.log('parse event script error, ', error)
  // }
}
